<template>
  <el-card class="page-container">
    <template #header>
      <div class="header" style="display: flex">
        <div class="title">{{ title }}</div>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-form class="form-inline" ref="employeeFormRef" :model="employeeForm" :rules="rules" label-width="120px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="employeeForm.username" disabled v-if="id"></el-input>
            <el-input v-model="employeeForm.username" v-else></el-input>
          </el-form-item>
          <el-form-item label="商家名" prop="name">
            <el-input v-model="employeeForm.name"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="employeeForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="身份证" prop="idNumber">
            <el-input v-model="employeeForm.idNumber"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="router.back()">返回</el-button>
            <el-button type="primary" @click="addHandle" v-if="title === '添加商家'">保存</el-button>
            <el-button type="primary" @click="saveHandle" v-if="+id === userStore.user.id">编辑</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>
<script setup lang="ts">
import { addBusinessAPI, getAdminBusinessAPI } from '@/api/admin/business'
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElForm, ElMessage, FormRules } from 'element-plus'
import { phoneValidator, idValidator } from '@/utils/validator'
import { EmployeeData } from '@/types/employee'
import { useUserStore } from '@/stores/userStore'
import { getBusinessAPI, putBusinessAPI } from '@/api/business/business'
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
// id
const id = computed(() => route.query.id as string)

// 标题
const title = ref('')
// 员工信息表单
const employeeForm = ref({} as EmployeeData)
onMounted(async () => {
  try {
    if (!id.value) {
      title.value = '添加商家'
    } else {
      title.value = '商家信息'
      // 获取员工信息
      if (userStore.rule === 'admin') {
        let { data } = await getAdminBusinessAPI(+id.value)
        employeeForm.value = data
      } else {
        let { data } = await getBusinessAPI(+id.value)
        employeeForm.value = data
      }
    }
  } catch (error) {
    console.log(error)
  }
})
// 表单实例
const employeeFormRef = ref<InstanceType<typeof ElForm> | null>(null)

// 校验规则
const rules = reactive<FormRules<typeof employeeForm>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    {
      min: 2,
      max: 10,
      message: '长度为2~10个非空字符且只能为数字或字母',
      trigger: 'submit',
    },
  ],
  name: [{ required: true, message: '请输入商家名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: phoneValidator, trigger: 'blur' },
  ],
  idNumber: [
    { required: true, message: '请输入身份证', trigger: 'blur' },
    { validator: idValidator, trigger: 'blur' },
  ],
})
const addHandle = async () => {
  try {
    await employeeFormRef.value?.validate()
    const params = {
      ...employeeForm.value,
    }
    await addBusinessAPI(params)
    ElMessage.success('添加成功')
    router.back()
  } catch (error) {
    console.log(error)
  }
}
// 保存员工信息
const saveHandle = async () => {
  employeeFormRef.value?.validate(async (vaild: boolean) => {
    if (vaild) {
      const params = {
        ...employeeForm.value,
      }
      await putBusinessAPI(params)
      ElMessage.success('修改成功')
      userStore.logout()
      router.push('/login')
    } else {
      ElMessage.error('表单校验失败')
    }
  })
}
</script>
<style scoped lang="scss"></style>
